package com.qf.driver.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.qf.common.bean.R;
import com.qf.common.dto.MqttUserDto;
import com.qf.common.model.MqttUser;
import com.qf.common.utils.SecuretUtil;
import com.qf.driver.feign.MqttUserFeign;
import com.qf.driver.service.MqttUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 千锋健哥
 */
@Service
public class MqttUserServiceImpl implements MqttUserService {

    @Autowired
    private MqttUserFeign mqttUserFeign;

    @Override
    public void addMqttUser(String tenantId) {
        //1. 根据租户id到mqtt_user表中查询是否已经有账号
        MqttUserDto dto = new MqttUserDto();
        dto.setTenantId(tenantId);
        R<List> mqttUserResult = mqttUserFeign.findAreaAll(dto);


        //2. 如果没有开通emqx服务器账号则开通
        if (mqttUserResult == null || mqttUserResult.getData().size() == 0) {
            MqttUser mqttUser = new MqttUser();
            mqttUser.setCreated(new Date());
            mqttUser.setUsername(tenantId);
            mqttUser.setPassword(SecuretUtil.encrypt3ToMD5(tenantId));
            mqttUser.setIsSuperuser(false);
            mqttUser.setTenantId(tenantId);
            mqttUserFeign.add(mqttUser);
        }
    }

}
